package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.beans.TableProcess;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.atguigu.gmall.realtime.utils.PhoenixUtil;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.*;
import java.util.*;

/**
 * @author Felix
 * @date 2023/6/6
 * 对主流和广播数据分别进行处理
 */
public class TableProcessFunction extends BroadcastProcessFunction<JSONObject, String, JSONObject> {

    private MapStateDescriptor<String, TableProcess> mapStateDescriptor;

    private Map<String,TableProcess> configMap = new HashMap<>();

    public TableProcessFunction(MapStateDescriptor<String, TableProcess> mapStateDescriptor) {
        this.mapStateDescriptor = mapStateDescriptor;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        //从配置表中读取配置信息  将配置信息预加载到map集合中
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //建立连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/gmall1219_config?" +
            "user=root&password=123456&useUnicode=true&characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");
        //获取数据库操作对象
        String sql = "select * from gmall1219_config.table_process where sink_type='dim'";
        PreparedStatement ps = conn.prepareStatement(sql);

        //执行SQL语句
        ResultSet rs = ps.executeQuery();

        //获取查询结果集对应的表元数据信息
        ResultSetMetaData metaData = rs.getMetaData();
        //处理结果集
        while(rs.next()){
            //定义一个json对象用于接收查询的结果
            JSONObject jsonObj = new JSONObject();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object columnValue = rs.getObject(i);
                jsonObj.put(columnName,columnValue);
            }
            TableProcess tableProcess = jsonObj.toJavaObject(TableProcess.class);
            configMap.put(tableProcess.getSourceTable(),tableProcess);
        }
        //释放资源
        rs.close();
        ps.close();
        conn.close();
    }

    //处理主流业务数据
    @Override
    public void processElement(JSONObject jsonObj, ReadOnlyContext ctx, Collector<JSONObject> out) throws Exception {
        // {"database":"gmall1219","xid":736,"data":{"tm_name":"Redmi1","create_time":"2021-12-14 00:00:00","id":1},"old":{"tm_name":"Redmi"},"commit":true,"type":"update","table":"base_trademark","ts":1686102177}
        // System.out.println(jsonObj);
        //获取广播状态
        ReadOnlyBroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        //获取当前处理的数据 对应的业务数据库表的表名
        String table = jsonObj.getString("table");
        //根据表名到广播状态中获取对应的配置信息
        TableProcess tableProcess = null;

        if ((tableProcess = broadcastState.get(table)) != null
            ||(tableProcess = configMap.get(table)) != null) {
            //如果配置信息不为空  说明是维度数据  传递到下游去
            // {"tm_name":"苹果111","create_time":"2021-12-14 00:00:00","logo_url":"/static/default.jpg2323","id":2}
            JSONObject dataJsonObj = jsonObj.getJSONObject("data");

            //在向下游传递数据前  过滤不需要传递的属性
            // {"tm_name":"苹果111","id":2}
            String sinkColumns = tableProcess.getSinkColumns();
            filterColumn(dataJsonObj, sinkColumns);

            //在向下游传递数据前   补充输出的目的地
            // {"tm_name":"苹果111","sink_table":"dim_base_trademark","id":2}
            String sinkTable = tableProcess.getSinkTable();
            dataJsonObj.put("sink_table", sinkTable);

            //在向下游传递数据前  补充操作类型
            String type = jsonObj.getString("type");
            dataJsonObj.put("type",type);
            //只需要将data过滤出来，传递到下游即可  data中存放的是业务数据库维度表中影响的这条记录
            out.collect(dataJsonObj);
        }
    }

    //过滤不需要向下游传递的属性
    // {"tm_name":"苹果111","create_time":"2021-12-14 00:00:00","logo_url":"/static/default.jpg2323","id":2}
    // sinkColumns:id,tm_name
    private void filterColumn(JSONObject dataJsonObj, String sinkColumns) {
        String[] fieldArr = sinkColumns.split(",");
        List<String> fieldList = Arrays.asList(fieldArr);
        Set<Map.Entry<String, Object>> entrySet = dataJsonObj.entrySet();
        entrySet.removeIf(entry -> !fieldList.contains(entry.getKey()));
    }

    //处理广播流配置数据
    //"op":"r": {"before":null,"after":{"source_table":"activity_info","source_type":"ALL","sink_table":"dim_activity_info","sink_type":"dim","sink_columns":"id,activity_name,activity_type,activity_desc,start_time,end_time,create_time","sink_pk":"id","sink_extend":null},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":0,"snapshot":"false","db":"gmall1219_config","sequence":null,"table":"table_process","server_id":0,"gtid":null,"file":"","pos":0,"row":0,"thread":null,"query":null},"op":"r","ts_ms":1686039033812,"transaction":null}
    //"op":"c": {"before":null,"after":{"source_table":"aaa","source_type":"ALL","sink_table":"dim_a","sink_type":"dim","sink_columns":"id,name","sink_pk":"id","sink_extend":null},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1686039145000,"snapshot":"false","db":"gmall1219_config","sequence":null,"table":"table_process","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":7520834,"row":0,"thread":null,"query":null},"op":"c","ts_ms":1686039144626,"transaction":null}
    //"op":"u": {"before":{"source_table":"aaa","source_type":"ALL","sink_table":"dim_bbb","sink_type":"dim","sink_columns":"id,name","sink_pk":"id","sink_extend":null},"after":{"source_table":"aaa","source_type":"ALL","sink_table":"dim_bbb","sink_type":"dim","sink_columns":"id,name,age","sink_pk":"id","sink_extend":null},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1686039247000,"snapshot":"false","db":"gmall1219_config","sequence":null,"table":"table_process","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":7521609,"row":0,"thread":null,"query":null},"op":"u","ts_ms":1686039246661,"transaction":null}
    //"op":"d": {"before":{"source_table":"aaa","source_type":"ALL","sink_table":"dim_bbb","sink_type":"dim","sink_columns":"id,name,age","sink_pk":"id","sink_extend":null},"after":null,"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1686039321000,"snapshot":"false","db":"gmall1219_config","sequence":null,"table":"table_process","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":7522013,"row":0,"thread":null,"query":null},"op":"d","ts_ms":1686039320393,"transaction":null}
    @Override
    public void processBroadcastElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
        //为了操作方便  将json字符串转换为json对象
        JSONObject jsonObj = JSON.parseObject(jsonStr);
        //获取广播状态
        BroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        String op = jsonObj.getString("op");
        if ("d".equals(op)) {
            //如果对配置表进行了删除操作  那么将对应的配置信息从广播状态中删除掉
            TableProcess before = jsonObj.getObject("before", TableProcess.class);
            String sinkType = before.getSinkType();
            if ("dim".equals(sinkType)) {
                String sourceTable = before.getSourceTable();
                broadcastState.remove(sourceTable);
                configMap.remove(sourceTable);
            }
        } else {
            //如果对配置表进行了删除外的其它操作  那么将对应的配置信息添加或者更新到广播状态中
            TableProcess after = jsonObj.getObject("after", TableProcess.class);
            String sinkType = after.getSinkType();
            if ("dim".equals(sinkType)) {
                //获取Phoenix中建表的表名
                String sinkTable = after.getSinkTable();
                //获取表中字段
                String sinkColumns = after.getSinkColumns();
                //获取建表主键
                String sinkPk = after.getSinkPk();
                //获取建表扩展
                String sinkExtend = after.getSinkExtend();

                //提前将Phoenix中的维度表创建出来
                checkTable(sinkTable, sinkColumns, sinkPk, sinkExtend);

                //将读取到的配置信息放到广播状态中
                String sourceTable = after.getSourceTable();
                broadcastState.put(sourceTable, after);
                configMap.put(sourceTable, after);
            }
        }
    }

    //提前创建维度表
    private void checkTable(String sinkTable, String sinkColumns, String sinkPk, String sinkExtend) {
        if (sinkPk == null) {
            sinkPk = "id";
        }
        if (sinkExtend == null) {
            sinkExtend = "";
        }
        //拼接建表语句
        StringBuilder createSql = new StringBuilder("create table if not exists " + GmallConfig.PHOENIX_SCHEMA + "." + sinkTable + "(");
        String[] columnArr = sinkColumns.split(",");
        for (int i = 0; i < columnArr.length; i++) {
            String columnName = columnArr[i];
            if(columnName.equals(sinkPk)){
                createSql.append(columnName + " varchar primary key");
            }else{
                createSql.append(columnName + " varchar ");
            }
            if(i < columnArr.length - 1){
                createSql.append(",");
            }
        }
        createSql.append(")" + sinkExtend);
        System.out.println("在Phoenix中执行的建表语句:" + createSql);

        PhoenixUtil.executeSql(createSql.toString());
    }
}
